//
//  CarTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/4.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "CarListTableViewController.h"

#import "PostUitls.h"
#import "CarbrandModel.h"
#import "CarResMode.h"
#import "CarpingpaiTableViewCell.h"
#import <UIImageView+WebCache.h>
#import <MJExtension.h>
#import "NumModel.h"
#import "LoadingView.h"
@interface CarListTableViewController ()
@property (nonatomic,strong) NSArray *array;
@property (nonatomic,strong) NSMutableArray *data;
@property (nonatomic,strong) NSMutableArray *setecionarray;
@property (nonatomic,strong) LoadingView *loadingview;
@property (nonatomic,strong) UIView *lableview;
@property (nonatomic,strong) UILabel *textlable;
@property (nonatomic,assign) CGFloat showtime;

@end

@implementation CarListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //改变索引的颜色
    self.tableView.sectionIndexColor = [UIColor grayColor];
    //改变索引选中的背景颜色
    self.tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexBackgroundColor=[UIColor clearColor];
    self.tableView.sectionIndexMinimumDisplayRowCount=25;
    UINib *nib=[UINib nibWithNibName:@"CarpingpaiTableViewCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"pingpai"];
   
    
    [self setupdata];
    [self setupLable];
    
}

-(LoadingView *)loadingview{
    if (_loadingview==nil) {
        _loadingview=[LoadingView loading];
        _loadingview.frame=self.tableView.frame;
        [self.tableView insertSubview:_loadingview atIndex:0];
    }
    return _loadingview;
}

-(void)showlableview:(NSString *)text{
    self.textlable.text=text;
    
    [self.navigationController.view addSubview:self.lableview];
    
}

-(void)hidelable{
    
    [self.lableview removeFromSuperview];
    
}
-(void)noticeBack{
    [self noticeCount];
}

-(NSMutableArray *)setecionarray{
    if (_setecionarray==nil) {
        _setecionarray=[NSMutableArray array];
    }
    return _setecionarray;
}

-(void)setupdata{
    self.loadingview.hidden=NO;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"all";
    [PostUitls Post:carlisturl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        
        CarResMode *res=[CarResMode carResWithDict:dict];
       
        [self setupsetection:res.data];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        self.loadingview.hidden=YES;
    }];
    
}





-(void)noticeCount{
    NSMutableDictionary *params2=[NSMutableDictionary dictionary];
    params2[@"action"]=@"count";
    
    [PostUitls Post:sscarurl parameters:params2 success:^(id response) {
        NSDictionary *dict=response;
        NumModel *mode=[NumModel objectWithKeyValues:dict];
        if ([mode.state integerValue]==400) {
            
            NSMutableDictionary *userinfo=[NSMutableDictionary dictionary];
            userinfo[@"num"]=mode.num;
            NSNotification *notice=[[NSNotification alloc]initWithName:NoticeCount object:nil userInfo:userinfo];
            [[NSNotificationCenter defaultCenter] postNotification:notice];
        }
    } failure:^(NSError *error) {
        
    }];

}
-(void)setupLable{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake((XHScreenwidth-60)*0.5,(XHScreenheight-60)*0.5, 60, 60)];
    view.backgroundColor=RGBACOLOR(30, 30, 30, 0.7);
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(12, 12, 60-24, 60-24)];
    lable.font=[UIFont systemFontOfSize:20];
    lable.textColor=[UIColor whiteColor];
    lable.textAlignment=NSTextAlignmentCenter;
    view.layer.cornerRadius=30;
    view.clipsToBounds=YES;
    [view addSubview:lable];
    self.textlable=lable;
    self.lableview=view;
}
-(void)setupsetection:(NSArray *)array{
    NSString *des=@"A";
    NSMutableArray *dataarray=[NSMutableArray array];
    [self.setecionarray addObject:@"#"];
    [self.setecionarray addObject:des];
    for (int i=0; i<array.count; i++) {
        CarbrandModel *car=array[i];
        
        if (![car.brand_desc isEqualToString:des]) {
            [self.data addObject:dataarray];
            dataarray=[NSMutableArray array];
            des=car.brand_desc;
            [self.setecionarray addObject:des];
        }
        [dataarray addObject:car];
        if (i==array.count-1) {
            [self.data addObject:dataarray];
        }
    }
    
    
    [self.tableView reloadData];
     self.loadingview.hidden=YES;
    NSLog(@"%@",self.data);
}

-(NSMutableArray *)data{
    if (_data==nil) {
        _data=[NSMutableArray array];
    }
    return _data;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSArray *array=self.data[section];
    return array.count;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return self.setecionarray;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.setecionarray[section+1];
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    [self showlableview:self.setecionarray[index]];
    self.showtime=1.0f;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.showtime=0.8f;
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.showtime==0.8f) {
            self.showtime=0.6f;
        }
        
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.showtime==0.6f) {
            self.showtime=0.4f;
        }
        
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.showtime==0.4f) {
            self.showtime=0.2f;
        }
        
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.showtime==0.2f) {
            [self hidelable];
        }
    });

    return index-1;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = UIColorWithRGB(242, 242, 242);
    
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:UIColorWithRGB(138, 138, 138)];
    [header.textLabel setFont:[UIFont systemFontOfSize:14]];
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    static NSString *ID=@"cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    if (cell==nil) {
//        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        cell.textLabel.font=[UIFont systemFontOfSize:14];
//        cell.imageView.width=30;
//        cell.imageView.height=30;
//    }
    CarpingpaiTableViewCell *cell=[CarpingpaiTableViewCell cellWithTablview:tableView];
    NSArray *array=self.data[indexPath.section];
    CarbrandModel *carmode=array[indexPath.row];
    cell.listtext.text=carmode.brand_name;
    cell.listtext.textColor=UIColorWithRGB(75, 75, 75);
    cell.listtext.font=[UIFont systemFontOfSize:14];
    NSString *url=[NSString stringWithFormat:@"%@%@",websitehosturl,[carmode.brand_logo stringByReplacingCharactersInRange:NSRangeFromString(@"./") withString:@"/"]];
    [cell.listicon sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placehoder"]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_checkeddelegate respondsToSelector:@selector(didCarPingPaiChecked:AndIndex:)]) {
        NSArray *array=self.data[indexPath.section];
        CarbrandModel *mode=array[indexPath.row];
        [_checkeddelegate didCarPingPaiChecked:mode AndIndex:indexPath];
        NSMutableDictionary *userinfo=[NSMutableDictionary dictionary];
        userinfo[@"brand"]=mode;
        NSNotification *notice=[[NSNotification alloc]initWithName:NoticeBrand object:nil userInfo:userinfo];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
